package com.gwsdk.paysdk.service;


import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gwsdk.open.GWApi;
import com.gwsdk.paysdk.bean.GWRoomSeatModel;
import com.gwsdk.paysdk.bean.MqttInfo;
import com.gwsdk.paysdk.entity.UserLogin;
import com.gwsdk.paysdk.utils.AppStatusManager;
import com.gwsdk.paysdk.utils.JsonUtil;
import com.gwsdk.paysdk.utils.ToastUtil;


import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class MqttService extends Service  {

    private final static String TAG = "EMQTT消息";

    private static final int qos = 0;
    private static MqttAndroidClient mqttAndroidClient;
    private MqttConnectOptions mMqttConnectOptions;
    private ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);

    private static final String TOPIC_BOSS = "boss";
    private static final String TOPIC_ROOM = "room";
    private static final String TOPIC_QIANG_TANG_GUO = "red_envelope_single_room_real_time_data";//抢糖果

    public static String sRoomId;

    public static String sUserId;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.e(TAG, "服务创建成功");
        scheduledExecutorService.scheduleWithFixedDelay(connectTask, 0, 10, TimeUnit.SECONDS);
    }

    private Runnable connectTask = new Runnable() {
        @Override
        public void run() {
            doClientConnection();
        }
    };

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public static void subscribeRoom(String roomId) {
        sRoomId = roomId;
        subscribe("room_" + roomId);
    }

    public static void cleanSubscribeRoom(String roomId) {
        cleanSubscribe("room_" + roomId);
        sRoomId = null;
    }

    public static void subscribeUser(String userId) {
        sUserId = userId;
        subscribe("user_" + userId);
    }

    public static void cleanSubscribeUser() {
        cleanSubscribe("user_" + sUserId);
        sUserId = null;
    }

    /**
     * 订阅主题
     *
     * @param topic
     */
    public static void subscribe(String topic) {
        try {
            if (isAlreadyConnected()) {
                IMqttToken subToken = mqttAndroidClient.subscribe(topic, qos);
                subToken.setActionCallback(new IMqttActionListener() {
                    @Override
                    public void onSuccess(IMqttToken asyncActionToken) {
                        Log.e(TAG, "主题订阅成功");
                    }

                    @Override
                    public void onFailure(IMqttToken asyncActionToken,
                                          Throwable exception) {
                        Log.e(TAG, "主题订阅失败");
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void cleanSubscribe(String topic) {
        try {
            if (isAlreadyConnected()) {
                IMqttToken subToken = mqttAndroidClient.unsubscribe(topic);
                subToken.setActionCallback(new IMqttActionListener() {
                    @Override
                    public void onSuccess(IMqttToken asyncActionToken) {
                        Log.e(TAG, "取消主题成功");
                    }

                    @Override
                    public void onFailure(IMqttToken asyncActionToken,
                                          Throwable exception) {
                        Log.e(TAG, "取消主题失败");
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化
     */
    private void init() {
        handler = new Handler();
        UserLogin user = AppStatusManager.getInstance().userLogin;

        String clientId = "android-" + user.getUserId() + "-";

        MqttInfo mqttInfo = AppStatusManager.getInstance().mqtt;
        String host = "tcp://"+mqttInfo.ip+":"+mqttInfo.port;

        if (mqttAndroidClient == null) {
            mqttAndroidClient = new MqttAndroidClient(this, host, clientId);
            mqttAndroidClient.setCallback(mqttCallback);
        }
        mMqttConnectOptions = new MqttConnectOptions();
        mMqttConnectOptions.setCleanSession(true); //设置是否清除缓存
        mMqttConnectOptions.setConnectionTimeout(10); //设置超时时间，单位：秒
        mMqttConnectOptions.setKeepAliveInterval(10); //设置心跳包发送间隔，单位：秒
    }

    private synchronized void doClientConnection() {
        Log.e("doClientConnection", "doClientConnection");
        if (!isAlreadyConnected() && isConnectIsNomarl()) {
            try {
                releaseMQTT();
                init();
                mqttAndroidClient.connect(mMqttConnectOptions, null, iMqttActionListener);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 是否连接
     *
     * @return
     */
    public static boolean isAlreadyConnected() {
        if (mqttAndroidClient != null) {
            try {
                return mqttAndroidClient.isConnected();
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        } else {
            return false;
        }
    }

    public static void closeConnection() {
        if (mqttAndroidClient == null ) return;
        if (mqttAndroidClient.isConnected()) {
            try {
                IMqttToken disconnect = mqttAndroidClient.disconnect();
                disconnect.setActionCallback(new IMqttActionListener() {
                    @Override
                    public void onSuccess(IMqttToken asyncActionToken) {

                    }

                    @Override
                    public void onFailure(IMqttToken asyncActionToken, Throwable exception) {

                    }
                });
            } catch (MqttException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 判断网络是否连接
     */
    private boolean isConnectIsNomarl() {
        return true;
    }


    private Handler handler;
    //MQTT是否连接成功的监听
    private IMqttActionListener iMqttActionListener = new IMqttActionListener() {

        @Override
        public void onSuccess(IMqttToken arg0) {
            time = 0;
            Log.e(TAG, "链接状态成功");
            if (sRoomId != null) {
                subscribeRoom(sRoomId);
            }
            subscribe(TOPIC_BOSS);
            subscribe(TOPIC_ROOM);
            subscribe(TOPIC_QIANG_TANG_GUO);
            subscribeUser(AppStatusManager.appStatusManager.userLogin.getUserId());
        }

        @Override
        public void onFailure(IMqttToken arg0, Throwable arg1) {
            arg1.printStackTrace();
            if (arg1 instanceof MqttException) {
                MqttException mqttException = (MqttException) arg1;
                mqttException.printStackTrace();
                Log.e(TAG, "链接状态失败" + mqttException.getMessage());
            }

            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    GWApi.getApi().getContext().runOnUiThread(connectTask);
                }
            },time += 1000);
        }
    };

    private long time = 0;

    //订阅主题的回调
    private MqttCallback mqttCallback = new MqttCallback() {

        @Override
        public void messageArrived(String topic, MqttMessage message) throws Exception {
            Log.e(TAG, "收到的消息 主题：" + topic + "  收到的消息：" + message.toString());
            if (TOPIC_BOSS.equals(topic)) {

                return;
            }
            if (TOPIC_QIANG_TANG_GUO.equals(topic)) {

                return;
            }

            receiveMessage(topic, message.toString());
        }


        @Override
        public void deliveryComplete(IMqttDeliveryToken arg0) {

        }

        @Override
        public void connectionLost(Throwable arg0) {
            Log.e(TAG, "链接状态：链接断开");
            doClientConnection();

        }
    };


    @Override
    public void onDestroy() {
        try {

            scheduledExecutorService.shutdown();
            scheduledExecutorService = null;
            cleanSubscribeRoom(sRoomId);
            cleanSubscribeUser();
            cleanSubscribe(TOPIC_BOSS);
            cleanSubscribe(TOPIC_ROOM);
            cleanSubscribe(TOPIC_QIANG_TANG_GUO);
            releaseMQTT();
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onDestroy();
    }

    public synchronized void releaseMQTT() {
        if (mqttAndroidClient != null) {
            try {
                mqttAndroidClient.disconnect();
                mqttAndroidClient.unregisterResources();
                mqttAndroidClient = null;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                mqttAndroidClient = null;
            }
        }
    }

    private void receiveMessage(String topic, String data) {
        if (sRoomId != null && topic.startsWith("room_") && !topic.equals(String.format("room_%s", sRoomId))) {
            //不接收非当前房间的推送
            return;
        }
        JSONObject jsonObject = JSON.parseObject(data);
        int type = jsonObject.getIntValue("type");
        String message = jsonObject.getString("msg");
        GWRoomSeatModel model = JsonUtil.toObj(message,GWRoomSeatModel.class);
        if (model == null) return;
        List<GWRoomSeatModel> seatModels = AppStatusManager.getInstance().seatModels;
        switch (type) {
            case 5032: {//推送房间-上麦
                for (int i=0;i<seatModels.size();i++){
                    GWRoomSeatModel m = seatModels.get(i);
                    if (m.pit_number.equals(model.pit_number)){
                        m.isSeat = true;
                        m.nickname = model.nickname;
                        m.user_id = model.user_id;
                        m.head_picture = model.head_picture;
                        Collections.sort(seatModels);
                        AppStatusManager.getInstance().refreshSeatInfo();
                        return;
                    }

                }
            }
                break;
            case 5033://推送房间-下麦
                for (int i=0;i<seatModels.size();i++){
                    GWRoomSeatModel m = seatModels.get(i);
                    if (m.pit_number.equals(model.pit_number)){
                        m.isSeat = false;
                        Collections.sort(seatModels);
                        AppStatusManager.getInstance().refreshSeatInfo();
                        return;
                    }
                }
                break;
            case 5034://踢出房间
                UserLogin userLogin = AppStatusManager.getInstance().userLogin;
                String userId = userLogin.getVoice_id()+"";
                if (model.user_id.equals(userId)){
                    AppStatusManager.getInstance().seatModels = new ArrayList<>();
                    AppStatusManager.getInstance().roomInfo = null;
                    AppStatusManager.getInstance().refreshSeatInfo();
                    ToastUtil.show("你已被踢出语聊房");
                }
                break;


        }

    }
}




